package com.videoStream.video.controller;


import com.alibaba.fastjson.JSONObject;
import com.videoStream.video.cache.CacheUtil;
import com.videoStream.video.entity.AjaxResult;
import com.videoStream.video.pojo.CameraLive;
import com.videoStream.video.pojo.CameraPojo;
import com.videoStream.video.pojo.Config;
import com.videoStream.video.service.CameraService;
import com.videoStream.video.thread.CameraThread;
import com.videoStream.video.util.Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.rmi.CORBA.Util;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Title CameraController.java
 * @description controller
 * @time 2019年12月16日 上午9:00:27
 * @author wuguodong
 **/

@RestController
public class CameraController {

	private final static Logger logger = LoggerFactory.getLogger(CameraController.class);

	@Autowired
	public Config config;
	@Autowired
	private CameraService cameraService;

	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


	/**
	 *
	 * @param cameraPojo
	 * @return
	 */
	@PostMapping("/cameras")
		public AjaxResult openCamera1(CameraPojo cameraPojo){
		//参数校验

		if(StringUtils.isEmpty(cameraPojo.getIp()) || StringUtils.isEmpty(cameraPojo.getUsername()) || StringUtils.isEmpty(cameraPojo.getPassword())){
			return AjaxResult.error("参数不完整");
		}
		//rtsp类型为1时，校验rtsp地址是否存在
		if(cameraPojo.getBuildRtspType() == 1){
			if(StringUtils.isEmpty(cameraPojo.getRtsp())){
				return AjaxResult.error("rtsp地址不能为空");
			}
		}


		boolean network = cameraService.networkTest(cameraPojo.getIp(), cameraPojo.getPort());
		if(!network){
			return AjaxResult.error("socket连接错误");
		}
		CameraLive cameraLive = cameraService.openCamera(cameraPojo);
		if(cameraLive == null){
			return AjaxResult.error("打开视频流失败,请稍后再试");
		}
		return AjaxResult.success("打开视频流成功",cameraLive);
	}

	/**
	 * @Title: closeCamera
	 * @Description:关闭视频流
	 * @param tokens
	 * @return void
	 **/
	@RequestMapping(value = "/cameras/{tokens}", method = RequestMethod.DELETE)
	public void closeCamera(@PathVariable("tokens") String tokens) {
		if (null != tokens && !"".equals(tokens)) {
			cameraService.closeCamera(tokens);
		}
	}

	/**
	 * @Title: getCameras
	 * @Description:获取视频流
	 * @return Map<String, CameraPojo>
	 **/
	@GetMapping(value = "/cameras")
	public Map<String, CameraPojo> getCameras() {
		logger.info("获取视频流信息：" + CacheUtil.STREATMAP.toString());
		return CacheUtil.STREATMAP;
	}

	/**
	 * @Title: keepAlive
	 * @Description:视频流保活
	 * @param tokens
	 * @return void
	 **/
	@PutMapping(value = "/cameras/{tokens}")
	public void keepAlive(@PathVariable("tokens") String tokens) {
		// 校验参数
		if (null != tokens && !"".equals(tokens)) {
			String[] tokenArr = tokens.split(",");
			for (String token : tokenArr) {
				CameraPojo cameraPojo = new CameraPojo();
				// 直播流token
				if (null != CacheUtil.STREATMAP.get(token)) {
					cameraPojo = CacheUtil.STREATMAP.get(token);
					// 更新当前系统时间
					cameraPojo.setOpentime(simpleDateFormat.format(new Date()));
					logger.info("保活成功 设备信息：[ip：" + cameraPojo.getIp() + " channel:" + cameraPojo.getChannel()
							+ " stream:" + cameraPojo.getStream() + " starttime:" + cameraPojo.getStarttime()
							+ " endtime:" + cameraPojo.getEndtime() + " url:" + cameraPojo.getUrl() + "]");
				}
			}
		}
	}

	/**
	 * @Title: getConfig
	 * @Description: 获取服务信息
	 * @return Map<String, Object>
	 **/
	@GetMapping(value = "/status")
	public Map<String, Object> getConfig() {
		// 获取当前时间
		long nowTime = System.currentTimeMillis();
		String upTime = (nowTime - CacheUtil.STARTTIME) / (1000 * 60 * 60) + "h"
				+ (nowTime - CacheUtil.STARTTIME) % (1000 * 60 * 60) / (1000 * 60) + "m"
				+ (nowTime - CacheUtil.STARTTIME) % (1000 * 60 * 60) / (1000) + "s";
		logger.info("获取服务信息：" + config.toString() + ";服务运行时间：" + upTime);
		Map<String, Object> status = new HashMap<String, Object>();
		status.put("config", config);
		status.put("uptime", upTime);
		return status;
	}

}
